import * as fs from "fs";
import * as path from "path";

// 服务列表一次构建
function buildService() {
    const servicePaht = path.resolve(__dirname, "../src/service");
    const serviceFileList = fs.readdirSync(servicePaht).filter((file) => {
        return !/\.map$/.test(file);
    }).map((file) => {
        const fileName = path.basename(file, path.extname(file));
        const serviceName = fileName.replace(/-(\w)/g, function () {
            return arguments[1].toUpperCase();
        });
        return { fileName, serviceName };
    });

    const serviceImportContent = serviceFileList.map((file) => {
        return `import ${ file.serviceName } from "./service/${ file.fileName }";`;
    }).join("\n");

    const serviceExportContent = `export default {\n${ serviceFileList.map((file) => {
        return `    "${ file.fileName }": ${ file.serviceName },`;
    }).join("\n") }\n}`;

    fs.writeFileSync(path.resolve(__dirname, "../src/serviceSet.ts"), `${ serviceImportContent }\n\n${ serviceExportContent };`);
}

// 插件列表一次构建
function buildExtension() {
    const extensionPath = path.resolve(__dirname, "../src/extension");
    const extensionFileList = fs.readdirSync(extensionPath);

    const extensionImportContent = extensionFileList.map((file) => {
        return `import ${ file } from "./extension/${ file }/app";`;
    }).join("\n");

    const extensionExportContent = `export default {\n${ extensionFileList.map((file) => {
        return `    ${ file },`;
    }).join("\n") }\n}`;

    fs.writeFileSync(path.resolve(__dirname, "../src/extensionSet.ts"), `${ extensionImportContent }\n\n${ extensionExportContent };`);
}

function isDir(path): Promise<boolean> {
    return fs.promises.stat(path).then((stats) => {
        return stats.isDirectory();
    });
}

// 一次同步
async function asyncNotTs() {
    const source = path.resolve(`${__dirname}/../src`);
    const to = path.resolve(`${__dirname}/../out`);
    const fileList: string[] = [];
    try {
        await fs.promises.access(path.resolve(__dirname, "../out/extension"))
    } catch (error) {
        await fs.promises.mkdir(path.resolve(__dirname, "../out/extension"));
    }
    let dirList: string[] = [];
    const task = [path.resolve(__dirname, "../src/extension")];
    while (task.length !== 0) {
        const dir = task.pop();
        const list = await fs.promises.readdir(dir);
        for (const file of list) {
            const filePath = path.resolve(__dirname, dir, file);
            if (await isDir(filePath)) {
                dirList.push(filePath.replace(source, to));
                task.push(filePath);
            } else if (path.extname(filePath) !== ".ts") {
                fileList.push(filePath);
            }
        }
    }
    for (const dir of dirList) {
        try {
            await fs.promises.access(dir)
        } catch (error) {
            await fs.promises.mkdir(dir, { recursive: true });
        }
    }
    await Promise.all(fileList.map((filePath) => {
        return new Promise(() => {
            return fs.promises.copyFile(filePath, filePath.replace(source, to));
        });
    }));
}

buildService();
buildExtension();
asyncNotTs();